package nl.justobjects.pushlet.core;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class GZipFilter implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        if (isGZipEncoding(req)) {
            res.setBufferSize(128);
            res.setHeader("Content-Encoding", "gzip");
            GZipResponse zipResponse = new GZipResponse(res);
            chain.doFilter(request, zipResponse);
            zipResponse.flush();
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

    /**
     * 判断浏览器是否支持GZIP
     *
     * @param request
     * @return
     */
    private static boolean isGZipEncoding(HttpServletRequest request) {
        boolean flag = false;
        String encoding = request.getHeader("Accept-Encoding");
        if (encoding != null && encoding.indexOf("gzip") != -1) {
            flag = true;
        }
        return flag;
    }

}
